"""处理数据层，将前端的数据传入到本层进行处理，处理过程和结果将显示在控制台界面"""

'''
self.infos = {
'20-20时累计降水量_R值结果":
                    {
                        '50529':[R1前，R1后，R2前，R2后]
                    }
'8-20时累计降水量_R值结果':
                    {
                        '5331':[]
                    }   
}

'''

import copy
from commonData import Data as data
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
import os
import math
from statistics import mean


class Data:
    def __init__(self):
        self.infos = {}  # 存放所有数据
        self.total_infos = {}  # 各个年份的infos
        self.stationInfos = {}  # 存放各个站点对应着的经度纬度，观测
        self.beta_alpha = {}  # 存放beta和alpha的值
        self.years_data = {}  # 存放年份数据的
        self.years_total = {}  # 一年所有的降水总量
        self.month_data = {}  # 存放一个月的数量
        self.rain_data = {}  # 存放eroP的值

    @staticmethod
    def get_sw(datas):
        for k in range(datas.count(None)):  # 除去data中的None
            datas.remove(None)
        r1, r2 = 0, 0
        for d in datas[:15]:
            if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                r1 += data.sw_a1 * float(d) + data.sw_a2 * math.pow(float(d), 2)

        for d in datas[15:]:
            if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                r2 += data.sw_a1 * float(d) + data.sw_a2 * math.pow(float(d), 2)
        return r1 * data.sw_turn_a, r2 * data.sw_turn_a  # 最终结果乘以转换系数

    @staticmethod
    def get_r(alpha, datas):
        for k in range(datas.count(None)):  # 除去data中的None
            datas.remove(None)
        r1, r2 = 0, 0
        for d in datas[:15]:
            if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                r1 += alpha * math.pow(float(d), data.exp1)

        for d in datas[15:]:
            if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                r2 += alpha * math.pow(float(d), data.exp1)
        return r1, r2

    @staticmethod
    def get_beta_alpha(pd12, py12):
        if not data.pd12:
            data.beta = data.a1 + data.a3 / py12
        elif not data.py12:
            data.beta = data.a1 + data.a2 / pd12
        else:
            if pd12 == 0 and py12 == 0:  # 根据pd12和py12得出beta的值
                data.beta = data.a1
            elif pd12 == 0:
                data.beta = data.a1 + data.a3 / py12
            elif py12 == 0:
                data.beta = data.a1 + data.a2 / pd12
            else:
                data.beta = data.a1 + data.a2 / pd12 + data.a3 / py12
        alpha = data.alpha * pow(data.beta, data.exp2)  # 得出alpha参数的值
        return alpha

    @staticmethod
    def get_m(datas, pd12, py12):
        for k in range(datas.count(None)):  # 除去data中的None
            datas.remove(None)
        m1, m2 = 0, 0
        alpha = Data.get_beta_alpha(pd12, py12)
        for d in datas[:15]:
            if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                m1 += alpha * pow(float(d), data.beta)  # 核心计算公式

        for d in datas[15:]:  # 计算后16个
            if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                m2 += alpha * pow(float(d), data.beta)  # 核心计算公式
        return m1, m2, alpha

    def get_abnormal(fun):
        def abnormal(self, *args, **kwargs):
            try:
                fun(self, *args, **kwargs)
            except Exception as e:
                if "WinError" in str(e):
                    print("\n*异常，请检查文件输入是否正确*\n")
                else:
                    print("异常信息:{},异常方法:{}".format(e, fun.__name__))

        return abnormal  # 没有返回值

    # 计算最终值

    @get_abnormal
    def get_py_data(self, one_year_data):
        for key in one_year_data.keys():
            for station, value in one_year_data[key].items():
                result = sum(value)
                data.py_data[key][station].append(result)

    # 计算pd/py的值
    @get_abnormal
    def start_cal_pd_and_py(self):
        print("=" * 9, "计算{}\{}".format('pd' + data.pd_number, 'py' + data.pd_number), "=" * 9)
        three_types = data.names  # 三个要计算的值
        if len(data.py_data) == 0:  # 如果内部没有值，那么就要重新计算
            excel_file = "{}_{}{}ok.xlsx"
            flag = 1
            for year in data.years:  # 所有年份
                one_year_data = {}
                for month in range(1, 12 + 1):  # 年份下对应着的月份数
                    m = str(month) if month >= 10 else ('0' + str(month))
                    file = excel_file.format(data.TYPE, year, m)  # TTPE指的是PRE、TEM这些
                    if os.path.exists(data.in_folder + "\\" + file):  # 如果该文件存在
                        print("正在处理:{}".format(file))
                        wb = data.dict_of_all_excel[file]
                        ws = wb[three_types[0]]
                        if flag == 1:
                            first_line = ws["A" + "1" + ":" + get_column_letter(ws.max_column) + "1"]  # A1:AK1
                            first_line = [x.value for x in first_line[0]]  # 获取值['区站号', '经度', '纬度', '观测场拔海高度', '年', '月'
                            first_line.insert(0, -1)  # 这一步为了后续获取1日，2日这些对应着的字母。
                            day1, max_day = get_column_letter(first_line.index('1日')), 'AO'  # F2:AK2
                            station_index, altitude = get_column_letter(first_line.index('区站号')), get_column_letter(first_line.index('观测场拔海高度'))  # 获取区站号--观测场海拔高度之间的所有数值
                            flag = 0
                        for ws_name in three_types:
                            ws = wb[ws_name]
                            pdkey = ws_name + '_{}结果'.format('pd')
                            pykey = ws_name + '_{}结果'.format('py')
                            if pdkey not in data.pd_data.keys():
                                data.pd_data[pdkey] = {}  # pd_data: pd12的数据
                            if pykey not in data.py_data.keys():  # py_data: py12的数据
                                data.py_data[pykey] = {}  #
                            if pykey not in one_year_data.keys():
                                one_year_data[pykey] = {}

                            for row in range(2, ws.max_row + 1):
                                station = ws['A' + str(row)].value
                                if station not in data.pd_data[pdkey]:
                                    data.pd_data[pdkey][station] = []  # 将每一个station对应着的数据设为列表的形式
                                if station not in data.py_data[pykey]:
                                    data.py_data[pykey][station] = []
                                if station not in one_year_data[pykey]:  # 记录一年的数据的字典
                                    one_year_data[pykey][station] = []

                                self.stationInfos[station] = [x.value for x in ws["{}{}:{}{}".format(station_index, str(row), altitude, str(row))][0]]
                                for x in ws["{}{}:{}{}".format(day1, str(row), max_day, str(row))][0]:
                                    info = x.value
                                    if (str(info).isdigit() == True or '.' in str(info)) and float(info) >= data.max_day_rain_num:  # 如果大于设定的降水量值
                                        if data.user_value == False:  # 是否为用户自定义
                                            data.pd_data[pdkey][station].append(float(info))  # 将数据添加进pd_data
                                            one_year_data[pykey][station].append(float(info))
                if data.user_value == False:  # 如果是用户自定的值
                    Data.get_py_data(self, one_year_data)
            if data.user_value == False:
                for key in data.py_data.keys():
                    for station, value in data.py_data[key].items():
                        if station not in data.modify_year:  # 若station不在该字典中
                            data.modify_year[station] = 0  # 需要修正的年数
                        count = 0
                        total = 0
                        for v in value:
                            if v != 0:
                                total += v
                                count += 1
                        if count == 0:  # 如果所有的年份数值都为0了，证明没有一年数据符合要求
                            data.py_data[key][station] = 0
                        else:
                            data.py_data[key][station] = float(total/count)  # 否则计算符合要求的年份
                        data.modify_year[station] = count
                for key in data.pd_data.keys():
                    for station, value in data.pd_data[key].items():
                        if len(data.pd_data[key][station]) == 0:
                            data.pd_data[key][station] = 0  # 将pdNum设为0,这里没有值
                        else:
                            data.pd_data[key][station] = mean(value)
        else:
            print("计算{}\{}已完成".format('pd' + data.pd_number, 'py' + data.pd_number))
        Data.finally_cal(self)

    @get_abnormal
    def finally_cal(self):
        print("=" * 15, "计算R值", "=" * 15)
        month_index = [0]
        a1 = 0
        a2 = 1
        for i in range(1, 13):
            month_index.append([a1, a2])
            a1 = a2 + 1
            a2 = a1 + 1

        three_types = data.names  # 三个要计算的值
        excel_file = data.in_folder + "\\{}"
        # excel_file = excel_file.format(data.TYPE) + "_{}{}ok.xlsx"
        excel_file = "{}_{}{}ok.xlsx"
        flag = 1  # 用来控制第一次获取变量的值，省去大量的不必要的计算。
        for year in data.years:
            self.infos = {}  # 计算下一年的时候重新赋值
            self.stationInfos = {}  # 存放各个站点对应着的经度纬度，观测
            self.rain_data = {}
            if year not in self.total_infos.keys():
                self.total_infos[year] = {}
            lose_month = []  # 丢失的月份
            save_folder = data.out_folder + "\\{}to{}{}{}mm".format(data.years[0], data.years[-1], data.recent[:2],str(data.max_day_rain_num))  # 存放文件的文件夹名字
            save_file = save_folder + '\\R{}年{}模型{}mm.xlsx'.format(year, data.recent[:2], str(data.max_day_rain_num))
            if os.path.exists(save_folder) == False:
                os.makedirs(save_folder)
            for month in range(1, 12 + 1):
                m = str(month) if month >= 10 else ('0' + str(month))
                file = excel_file.format(data.TYPE, year, m)
                if os.path.exists(data.in_folder + "\\" + file) == True:  # 如果该文件存在
                    print("正在处理:{}".format(file))
                    wb = data.dict_of_all_excel[file]
                    if data.recent == '水利部门模型':
                        alpha1 = data.warmth if int(month) in [5, 6, 7, 8, 9] else data.cold
                    ws = wb[three_types[0]]
                    if flag == 1:
                        first_line = ws["A" + "1" + ":" + get_column_letter(ws.max_column) + "1"]  # A1:AK1
                        first_line = [x.value for x in first_line[0]]  # 获取值['区站号', '经度', '纬度', '观测场拔海高度', '年', '月'
                        first_line.insert(0, -1)  # 这一步为了后续获取1日，2日这些对应着的字母。
                        day1, max_day = get_column_letter(first_line.index('1日')), 'AO'  # F2:AK2
                        station_index, altitude = get_column_letter(first_line.index('区站号')), get_column_letter(first_line.index('观测场拔海高度'))  # 获取区站号--观测场海拔高度之间的所有数值
                        flag = 0
                    for ws_name in three_types:
                        ws = wb[ws_name]  # 一个一个计算three_types的值
                        key = ws_name + "_R值"
                        _pd = data.pd_number if data.user_value == False else '自定义'
                        _py = data.pd_number if data.user_value == False else '自定义'
                        pdkey = ws_name + '_{}结果'.format('pd')
                        pykey = ws_name + '_{}结果'.format('py')

                        if key not in self.infos.keys():  # 如果key不在内，则新建一个，否则不要新建，避免数据损失
                            self.infos[key] = {}  # 给每一个sheetname设定为字典类型
                            self.beta_alpha[key] = {}
                            self.month_data[key] = {}
                            self.rain_data[key] = {}
                        if ws_name not in self.years_data.keys():
                            self.years_data[ws_name] = {}
                        if ws_name not in self.years_total.keys():
                            self.years_total[ws_name] = {}
                        for row in range(2, ws.max_row + 1):
                            station = ws['A' + str(row)].value

                            if station not in self.years_data[ws_name]:  # 一年中大于等于降雨侵蚀量的值
                                self.years_data[ws_name][station] = {}
                            if year not in self.years_data[ws_name][station]:
                                self.years_data[ws_name][station][year] = 0

                            if station not in self.years_total[ws_name]:  # 一年的总量，不管大小
                                self.years_total[ws_name][station] = {}
                            if year not in self.years_total[ws_name][station]:
                                self.years_total[ws_name][station][year] = 0

                            if station not in self.infos[key]:
                                self.infos[key][station] = ['缺失' for x in range(24)]  # 如果该区站号不在，则表示是新的
                            if station not in self.beta_alpha[key]:
                                self.beta_alpha[key][station] = []
                            if station not in self.month_data[key]:
                                self.month_data[key][station] = ['缺失' for x in range(12)]
                            if station not in self.rain_data[key]:
                                self.rain_data[key][station] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]  # 12个月+1年的总数据列表
                            self.stationInfos[station] = [x.value for x in ws["{}{}:{}{}".format(station_index, str(row), altitude, str(row))][0]]
                            oneLine = [x.value for x in ws["{}{}:{}{}".format(day1, str(row), max_day, str(row))][0]]  # ws[exp2] 是一个元祖，[0]是取出第一个值
                            """计算eroP值"""
                            for d in oneLine:
                                if (str(d).isdigit() == True or '.' in str(d)) and float(d) >= data.max_day_rain_num:
                                    self.rain_data[key][station][month] += float(d)
                                    self.years_data[ws_name][station][year] += float(d)
                                if str(d).isdigit() == True or '.' in str(d):
                                    self.years_total[ws_name][station][year] += float(d)  # 存放一年的总量
                            self.rain_data[key][station][13] = sum(self.rain_data[key][station][1:12 + 1])  # 计算全年综合


                            """计算各个模型值"""
                            index1, index2 = month_index[month][0], month_index[month][1]
                            if data.recent == '水利部门模型':
                                R1, R2 = Data.get_r(alpha1, oneLine)  # 还是以对应着的alpha计算的
                                ## 采用插入的方法，插入到对应的月份中去
                                self.infos[key][station][index1] = R1
                                self.infos[key][station][index2] = R2
                                self.month_data[key][station][month - 1] = R1 + R2  # 将上下半月之和相加

                            elif data.recent == '西南大学模型':
                                SW1, SW2 = Data.get_sw(oneLine)
                                self.infos[key][station][index1] = SW1
                                self.infos[key][station][index2] = SW2
                                self.month_data[key][station][month - 1] = SW1 + SW2
                            else:
                                if data.user_value == True:  # 如果用户自定义的不为空，那么就
                                    if station in data.user_pdpy_data.keys():
                                        pd, py = data.user_pdpy_data[station]  # 两个数字的列表
                                    else:
                                        pd, py = '缺失', '缺失'
                                else:
                                    pd = data.pd_data[pdkey][station]  # pd 与 py 的值，这里是根据降雨量的阈值来设置的
                                    py = data.py_data[pykey][station]
                                if pd == '缺失':
                                    self.infos[key][station][index1] = -99.000  # 缺失就赋值为 -99.000
                                    self.infos[key][station][index2] = -99.000
                                    self.beta_alpha[key][station] = [-99.000, -99.000, -99.000, -99.000]
                                    self.month_data[key][station][month - 1] = -99.000
                                else:
                                    M1, M2, alpha2 = Data.get_m(oneLine, pd, py)
                                    self.infos[key][station][index1] = M1
                                    self.infos[key][station][index2] = M2
                                    self.beta_alpha[key][station] = [pd, py, data.beta, alpha2]
                                    self.month_data[key][station][month - 1] = M1 + M2
                else:  # 如果该月不存在，则该月的所有区站号的值都设为空
                    lose_month.append(month)
            for key in self.infos.keys():
                for station, datas in self.infos[key].items():
                    result = 0.0
                    for d in datas:
                        if str(d).isdigit() == True or '.' in str(d):
                            result += float(d)
                    self.infos[key][station].append(result)

            for month in lose_month:  # 处理丢失的月份的
                # index1, index2 = month_index[month][0], month_index[month][1]
                for key in self.infos.keys():
                    for station in self.infos[key].keys():
                        self.month_data[key][station].insert(month - 1, '缺失')
            wb = Workbook()
            ws = wb['Sheet']
            wb.remove(ws)
            a1, a2 = first_line.index('区站号'), first_line.index('观测场拔海高度') + 1
            filed_year = "{}M{}{}"  # 修改了格式，采用 2020M01前 的格式

            basic = first_line[a1:a2] + ['年']
            first_year_before = get_column_letter(len(basic) + 1)
            for month in range(1, 12 + 1):
                m = str(month) if month >= 10 else ('0' + str(month))
                basic += [filed_year.format(year, m, 'a'), filed_year.format(year, m, 'b')]
            basic += ['R{}'.format(year)]
            for month in range(1, 12 + 1):
                m = str(month) if month >= 10 else ('0' + str(month))
                basic += ['{}M{}'.format(year, m)]
            field_rain_data = "eroP{}M{}"
            for month in range(1, 12 + 1):
                m = str(month) if month >= 10 else ('0' + str(month))
                basic += [field_rain_data.format(year, m)]
            basic += ['eroP%s' % year]
            for key in self.infos.keys():
                new_name = key.split("_")[0] + data.recent[:2] + str(data.max_day_rain_num) + "mm_R值"
                ws = wb.create_sheet(new_name)
                ws.freeze_panes = 'A2'  # 分隔开后也要冻结窗口
                ws.append(basic)
                for station, info in self.infos[key].items():
                    temp = self.stationInfos[station] + [int(year)] + info + self.month_data[key][station] + self.rain_data[key][station][1:]  # 一个临时的数组，将数据添加进去
                    ws.append(temp)
                cells = ws[first_year_before + "2" + ":" + get_column_letter(ws.max_column) + str(ws.max_row)]  # 单元格范围E2到最后
                for row in cells:
                    for col in row:
                        col.number_format = "0.0000"  # 都设置为保留四位小数

            wb.save(save_file)
            self.total_infos[year] = copy.deepcopy(self.infos)  # 深拷贝这一年的数据过去
        for name in three_types:
            for station in self.years_data[name].keys():
                for year in data.years:
                    if year not in self.years_data[name][station]:
                        self.years_data[name][station][year] = '缺失'
        Data.cal_24month_1year_m(self, first_line)

    # 由于处理存放数据的方法都是一致的，所以写成一个方法。
    @get_abnormal
    def get_pd_and_py_wb(self, first_line, infos, last_desc):
        wb = Workbook()
        ws = wb['Sheet']
        wb.remove(ws)
        a1, a2 = first_line.index('区站号'), first_line.index('观测场拔海高度') + 1
        basic = first_line[a1:a2] + [last_desc]
        for key in infos.keys():
            wb.create_sheet(key)
            ws = wb[key]  # 获得sheet
            ws.freeze_panes = 'A2'  # 分隔开后也要冻结窗口
            ws.append(basic)  # 添加表头
            for station, value in infos[key].items():
                info = self.stationInfos[station] + [value]
                ws.append(info)
            Data.set_sheet_decimal_point(ws, len(basic), ws.max_column, 4)  # 对范围单元格内的数据保存四位数字
        return wb

    @get_abnormal
    def cal_24month_1year_m(self, first_line):  # 计算24个半月和每年的M值结果
        print("=" * 9, "处理M年月均值中", "=" * 9)
        # self.infos 指向了所有信息的变量，包括24个M半月和一年的总和的数据
        new_data_file = data.out_folder + "\\{}to{}{}\\".format(data.years[0], data.years[-1], data.recent[:2] + str(data.max_day_rain_num) + 'mm')  # 都是要放在这里的
        if os.path.exists(new_data_file) == False:
            os.makedirs(new_data_file)
        month_year_data = {}  # 24个月的
        month_12_result = {}  # 12个月的数据
        for year in self.total_infos.keys():  # key是年
            for ws_name in self.total_infos[year].keys():
                if ws_name not in month_year_data.keys():
                    month_year_data[ws_name] = {}  # 都是以字典的形式存放
                    month_12_result[ws_name] = {}
                for station, value in self.total_infos[year][ws_name].items():
                    if station not in month_year_data[ws_name].keys():  # 如果不在内部
                        month_year_data[ws_name][station] = []
                        month_12_result[ws_name][station] = []  # 存放12个月的数据
                        for i in range(0, len(value)):
                            v = value[i]
                            if not str(v).isdigit() and '.' not in str(v):  # 如果不是数字,则置为0
                                v = 0.0
                            if data.user_value == True and station not in data.user_pdpy_data.keys():  # 如果是用户自定义计算pdpy，并且station不在内，则赋值为 -99
                                v = -99
                            month_year_data[ws_name][station].append(float(v))  #
                        month_year_data[ws_name][station].append(1)  # 赋值，作为次数，也就是处理了几年的,添加在最后
                    else:
                        for i in range(0, len(value)):
                            v = value[i]
                            if not str(v).isdigit() and '.' not in str(v):  # 如果不是数字
                                v = 0
                            if data.user_value == True and station not in data.user_pdpy_data.keys():
                                v = 0.0
                            month_year_data[ws_name][station][i] += float(v)  # 如果，则元素相加即可
                        month_year_data[ws_name][station][-1] += 1  # 最后一个统计次数的数加1
        for key in month_year_data.keys():
            for station, value in month_year_data[key].items():
                for i in range(0, len(value[:-1])):
                    if data.user_value == True and station not in data.user_pdpy_data.keys():
                        month_year_data[key][station][i] /= 1
                    else:
                        month_year_data[key][station][i] /= value[-1]  # 除以最后一个计数的数字

        #  计算合并的年份
        for t in month_year_data.keys():
            for station, value in month_year_data[t].items():
                i = 0
                for v in value[:-2:2]:
                    if data.user_value == True and station not in data.user_pdpy_data.keys():
                        month_12_result[t][station].append(-99)
                    else:
                        month_12_result[t][station].append(value[i] + value[i + 1])
                    i += 2
        a1, a2 = first_line.index('区站号'), first_line.index('观测场拔海高度') + 1
        filed_year = "M{}{}"  # 修改了格式，采用 M01前 的格式 M03b
        basic = first_line[a1:a2]
        for month in range(1, 12 + 1):
            m = str(month) if month >= 10 else ('0' + str(month))
            basic += [filed_year.format(m, 'a'), filed_year.format(m, 'b')]  # M01a M01b M02a M02b的数据

        temp_field = "M{}"
        for month in range(1, 12 + 1):
            m = str(month) if month >= 10 else ('0' + str(month))
            basic += [temp_field.format(m)]

        basic += ['R多年_均']  # 水利部门不需要
        if data.recent == '北师大模型':  # 北师大模型
            _pd = data.pd_number if data.user_value == False else '自定义'
            _py = data.pd_number if data.user_value == False else '自定义'
            basic += ['pd' + str(_pd), 'py' + str(_py), 'beta', 'alpha']
        for year in data.years:  # 将年份数据写入进去
            basic += ['R' + str(year)]
        basic += ['处理年数']
        for year in data.years:  # 将年份数据写入进去
            basic += ['eroP' + str(year)]
        for year in data.years:  # 将一年总数据数据写入进去
            basic += ['P' + str(year) + 'all']
        wb = Workbook()
        ws = wb['Sheet']
        wb.remove(ws)
        for key in month_year_data.keys():
            new_name = key.split("_")[0] + data.recent[:2] + str(data.max_day_rain_num) + "mm_均值"
            wb.create_sheet(new_name)
            ws = wb[new_name]
            ws.freeze_panes = 'A2'  # 分隔开后也要冻结窗口
            ws.append(basic)  # 添加表头
            for station, value in month_year_data[key].items():
                if station in self.stationInfos:
                    temp = self.stationInfos[station] + value[:-2] + month_12_result[key][station] + [value[-2]] + self.beta_alpha[key][station]
                    for year in data.years:
                        if station in self.total_infos[year][key]:
                            temp += [self.total_infos[year][key][station][-1]]  # 加入R年
                        else:
                            temp += ['缺失']
                    ''' 加入年份数 '''
                    if data.user_value == False and len(data.modify_year) > 0 and data.modify_year[station] - int(value[-1]) != 0: # 用户自定义pdpy为False、修改年份-当前年份不为0
                        temp += [str(data.modify_year[station]) + " ({}年有0值)".format(int(value[-1]) - data.modify_year[station])]
                    else:
                        temp += [value[-1]]
                    for year in data.years:
                        temp += [self.years_data[key[:-3]][station][year]]  # 加入eroP2000 eroP2001年的年份数据。
                    for year in data.years:
                        if year in self.years_total[key[:-3]][station].keys():
                            temp += [self.years_total[key[:-3]][station][year]]  # 加入eroP2000 eroP2001年的年份数据。
                        else:
                            temp += ['缺失']
                    ws.append(temp)
            Data.set_sheet_decimal_point(ws, basic.index('M01a') + 1, ws.max_column, 3)  # 保留三位小数
            if data.recent == '北师大模型':
                Data.set_sheet_decimal_point(ws, basic.index('pd' + str(_pd)) + 1, basic.index('py' + str(_py)) + 1, 2)
            Data.set_sheet_decimal_point(ws, basic.index('处理年数') + 1, basic.index('处理年数') + 1, 0)
            Data.set_sheet_decimal_point(ws, basic.index('eroP' + str(data.years[0])) + 1, basic.index('eroP' + str(data.years[-1])) + 1, 1)

        new_data_file += 'R{}to{}{}mm均.xlsx'.format(data.years[0], data.years[-1], data.recent[:2] + str(data.max_day_rain_num))
        wb.save(new_data_file)

    @staticmethod
    def set_sheet_decimal_point(ws: "对应的表", index1: "从这", index2: "到这", num: "保留num位小数"):
        try:
            cells = ws[get_column_letter(index1) + "2" + ":" + get_column_letter(index2) + str(
                ws.max_row)]  # pd12和py12设定为保留两位小数的
            for row in cells:
                for col in row:
                    if num == 0:
                        col.number_format = "0"  # eroP保留一位小数
                    else:
                        col.number_format = "0." + "0" * num
        except Exception as e:
            print("异常信息:", e, "异常方法:set_sheet_decimal_point")
